package org.weather;

import java.util.ArrayList;

import java.util.Collections;
import java.util.Comparator;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

/**
 * Adapterul pentru clasa City(care e un String).
 * @author andrei
 *
 */
public class CityAdapter extends BaseAdapter {

	private Activity context;
	ArrayList<City> cities;
	/*sortam cu comparator, folosind algoritmul din Collections*/
	Comparator<City> comp;
	
	CityAdapter (Activity context)
	{
		this.context = context;
		cities = new ArrayList<City>();
		
		comp = new Comparator<City>(){
			@Override
			public int compare(City arg0, City arg1) {
				City c1 = arg0;
				City c2 = arg1;
				return c1.name.compareTo(c2.name);
			}
		};
	}
	
	/**
	 * Functia trebuie sa intoarca view-ul de pe pozitia position din lista.
	 * ConvertView este un element din lista ce nu mai este vizibil si 
	 * poate fi reutilizat.
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup list) {
		View element;
		
		if (convertView == null)
        {
        	LayoutInflater inflater = context.getLayoutInflater();
		    element = inflater.inflate(R.layout.city, null);
        }else element = convertView;
 
		TextView name = (TextView)element.findViewById(R.id.city_name);
		name.setText(cities.get(position).toString());
		
		return element;
	}
	
	/**
	 * Adauga un oras la lista.
	 * @param name
	 */
	public void add(String name){
		City city = new City(name);
		cities.add(city);
		Collections.sort(cities, comp);
		this.notifyDataSetChanged();
	}
	
	/**
	 * Scoate un oras din lista.
	 * @param index
	 */
	public void remove(int index){
		cities.remove(index);
		Collections.sort(cities, comp);
		this.notifyDataSetChanged();
	}
	
	/**
	 * 
	 * @param name
	 * @return true daca continte orasul name
	 */
	
	public boolean contains(String name){
		return cities.contains(new City(name));
	}
	
	@Override
	public int getCount() {
		return cities.size();
	}

	@Override
	public Object getItem(int index) {
		return cities.get(index);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}
}
